<--- %%NOBANNER%% --> samelabl.sas
 BackForward
%macro samelabl (fromData=, toData=);

  %* Copy labels of source to destination
  %* Richard A. DeVenezia, 12/22/99
  %*;

  %local this srcId dstId i nvars varname varnum varlabel labels lib mem rc;

  %let this = samelabl;

  %* open tables in utility mode;

  %let srcId = %sysfunc (open (&fromData,V));
  %let dstId = %sysfunc (open (&toData,V));

  %* create name='label' part of label statement for use in Proc DATASETS;
  %* only vars in both datasets will be in the statement;

  %if &srcId and &dstId %then %do;
    %let nvars = %sysfunc (attrn (&srcId, nvars));
    %do i = 1 %to &nvars;
      %let varname = %sysfunc (varname (&srcId, &i));
      %let varnum  = %sysfunc (varnum  (&dstId, &varname));
      %if &varnum %then %do;
        %let varlabel = %sysfunc (varlabel (&srcId, &i));
        %if %length (%superq (varlabel)) %then
          %let labels = &labels &varname = %str(%'%quote(&varlabel)%');
        %else
          %let labels = &labels &varname = ' ';
      %end;
    %end;

    %let lib = %sysfunc (attrc (&dstId, lib));
    %let mem = %sysfunc (attrc (&dstId, mem));

    %let srcId = %sysfunc (close (&srcId));
    %let dstId = %sysfunc (close (&dstId));

    proc datasets nolist lib=&lib;
      modify &mem;
      label &labels;
    quit;
  %end;
  %else %do;
    %if &srcId = 0
      %then %put ERROR: &this: Source [&fromData] could not be opened.;
      %else %let srcId = %sysfunc (close (&srcId));

    %if &dstId = 0
      %then %put ERROR: &this: Destination [&toDataination] could not be opened.;
      %else %let dstId = %sysfunc (close (&dstId));
  %end;

%mend samelabl;